package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
 * @ClassName KeyboardListenerDemo
 * @Description 键盘监听事件
 * @Author wangss
 * @date 2020.06.03 22:39
 * @Version 1.0
 */
public class KeyboardListenerDemo extends Application {

    private int index = 1;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        HBox hBox = new HBox(15);

        Button b1 = new Button("button1");
        Button b2 = new Button("button2");
        TextField tf = new TextField();

        Rectangle rec = new Rectangle(100, 100);
        rec.setFill(Color.RED);

        hBox.getChildren().addAll(b1, b2, tf, rec);

        an.getChildren().add(hBox);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();

        b1.setOnKeyPressed(event -> {
            /*System.out.println("character = " + event.getCharacter());
            System.out.println("事件类型 = " + event.getEventType());
            System.out.println("事件源 = " + event.getSource());
            System.out.println("事件目标 = " + event.getTarget());
            System.out.println("按键 = " + event.getText());
            System.out.println("ctrl = " + event.isControlDown());*/

            if (event.getCode().getName().equals(KeyCode.A.getName())) {
                // 一直按五次，结束
                if (index > 5) {
                    return;
                }
                System.out.println("按了 " + KeyCode.A.getName() + " 键");
            }
            index++;
        });

        b1.setOnKeyReleased(event -> {
            System.out.println("释放 " + event.getCode().getName() + " 键");
            index = 1;
        });

        // 这个方法是作用在有输入框得地方才可以使用
        tf.setOnKeyTyped(event -> System.out.println("character = " + event.getCharacter()));

        // rec添加键盘监听事件，需要强行设置焦点
        rec.setOnKeyPressed(event -> System.out.println("rec = " + event.getCode().getName()));
        rec.setOnMouseClicked(event -> rec.requestFocus());
    }
}
